package org.hot100_1;

import java.util.HashMap;

public class leetcode35 {
    class LRUCache{

        class Node {
            Node prev;
            Node next;
            int key,value;

            Node(int key,int value){
                this.key=key;
                this.value=value;
            }

        }
        HashMap<Integer,Node> map = new HashMap<>();

        Node dummy = new Node(0,0);

        private int capacity;
        public LRUCache(int capacity) {
            this.capacity=capacity;
            dummy.next=dummy;
            dummy.prev=dummy;
        }

        public int get(int key) {
            Node node = getNode(key);
            if (node==null){
                return -1;
            }else {
                return node.value;
            }
        }

        public void put(int key, int value) {
            Node node = getNode(key);
            if (node!=null){
                node.value=value;
                return;
            }

            Node newNode = new Node(key, value);
            map.put(key,newNode);
            putHeader(newNode);
            if (map.size()>capacity){
                map.remove(dummy.prev.key);
                removeNode(dummy.prev);
            }
        }

        private Node getNode(int key){
            if (!map.containsKey(key)){
                return null;
            }
            Node node = map.get(key);

            removeNode(node);

            putHeader(node);

            return node;
        }

        private void putHeader(Node node){
            node.prev=dummy;
            node.next=dummy.next;

            dummy.next=node;
            node.next.prev=node;
        }

        private void removeNode(Node node){
            node.prev.next=node.next;
            node.next.prev=node.prev;
        }
    }
}
